package test.top2.com.atguigu.utils;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import redis.clients.jedis.Jedis;
import test.top2.com.atguigu.common.GmallConfig;

import java.sql.Connection;
import java.util.List;

/**
 * ClassName: DimUtil
 * Package: test.top2.com.atguigu.utils
 * Description:
 *
 * @Author ChenJun(有志男青年)
 * @Create 2023/5/11 15:46
 * @Version 1.0
 */
public class DimUtil {

    @SneakyThrows
    public static JSONObject getDimInfo(Connection connection, String tableName, String id){

        //为了提高效率使用redis做旁路缓存
        Jedis jedis = JedisUtil.getJedis();

        //Key设计
        String redisKey = "DIM:"+tableName.toUpperCase()+":"+id;

        String dimInfoStr = jedis.get(redisKey);

        if (dimInfoStr != null){
            //重置过期时间
            jedis.expire(redisKey,24 * 3600);
            jedis.close();
            return JSON.parseObject(dimInfoStr);
        }

        //拼接sql
        String sql = "select * from "+ GmallConfig.HBASE_SCHEMA+"."+tableName+" where id = '"+id+"'";
        System.out.println("查询SQL为：" + sql);

        List<JSONObject> jsonObjects = JdbcUtil.queryList(connection, sql, JSONObject.class, false);


        //如果是第一次查询 将数据写入redis
        JSONObject dimInfo = jsonObjects.get(0);
        jedis.setex(redisKey,24* 3600,dimInfo.toJSONString());
        jedis.close();

        //返回结果
        return jsonObjects.get(0);

    }

    public static void main(String[] args) throws Exception {

        DruidPooledConnection connection = DruidDSUtil.getPhoenixConn();

        long start = System.currentTimeMillis();

        //145 123 115 116 117 120 117
        JSONObject dimBaseTrademark = getDimInfo(connection, "DIM_SPU_INFO", "14");
        long end = System.currentTimeMillis();

        //9  9  8  8   1  1  1  1
        JSONObject dimBaseTrademark2 = getDimInfo(connection, "DIM_SPU_INFO", "14");
        long end2 = System.currentTimeMillis();

        System.out.println(dimBaseTrademark);
        System.out.println(dimBaseTrademark2);
        System.out.println(end - start);
        System.out.println(end2 - end);

        connection.close();
    }
}
